package com.zhdl.hardware_contact.hardware_web.controller;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.network.entity.PortComm;
import com.project.network.entity.PortSocket;
import com.zhdl.common.util.BeanUtils;
import com.zhdl.common.util.WebResult;
import com.zhdl.hardware_contact.hardware_config.entity.ProjectConfiguration;
import com.zhdl.hardware_contact.hardware_config.entity.ProjectParameter;
import com.zhdl.hardware_contact.hardware_config.service.dto.ProjectConfigQueryCriteria;
import com.zhdl.hardware_contact.hardware_config.service.dto.ProjectParamQueryCriteria;
import com.zhdl.hardware_contact.hardware_param.entity.*;
import com.zhdl.hardware_contact.hardware_web.request.*;
import com.zhdl.hardware_contact.hardware_web.respone.HardwareCurrentMessageResp;
import com.zhdl.hardware_contact.hardware_web.respone.HardwareInfoConfigResp;
import com.zhdl.hardware_contact.hardware_web.respone.HardwareInfoViewResp;
import com.zhdl.hardware_contact.hardware_web.respone.ProjectConfigurationResp;
import com.zhdl.hardware_contact.hardware_web.service.HardwareAbsService;
import com.zhdl.hardware_contact.hardware_web.service.HardwareContactService;
import com.zhdl.hardware_contact.hardware_web.service.HardwareCurrentService;
import com.zhdl.modules.common.protocol_param.service.ProtocolParamService;
import com.zhdl.modules.common.warn.service.RunWarnService;
import com.zhdl.modules.demo.dglProcess.DGLMainProcess;
import com.zhdl.modules.demo.hardware_connect.ConnectManager;
import com.zhdl.modules.demo.testprocess.TestMainProcess;
import com.zhdl.modules.process.BaseProcess;
import com.zhdl.modules.process.ProcessStatusExchangeHolder;
import com.zhdl.modules.process.service.ProjectConfigProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.zhdl.common.ytools.springContext.CommonParmaOpt.*;


import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Slf4j
@RestController
@RequestMapping(path = "/api/hardware", produces = MediaType.APPLICATION_JSON_VALUE)
public class HardwareContactController {


    private static final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    private final Map<Integer, SseEmitter> sseEmitters = new ConcurrentHashMap<>();
    private long sseSeq;


    @Resource
    private HardwareContactService hardwareContactService;

    /*---------------------------------------- 项目配置 ----------------------------------------*/
    @Resource
    private ProtocolParamService protocolParamService;

    @Resource
    private HardwareAbsService hardwareAbsService;

    @Resource
    private ProjectConfigProcessService projectConfigProcessService;

    @Resource
    private HardwareCurrentService hardwareCurrentService;



    /**
     * 获取SSE序号
     */
    private long getSseSeq() {
        if (sseSeq > 65535L * 65535)
            sseSeq = 0;
        return sseSeq++;
    }

    /**
     * sse推送实时信息
     *
     * @param id
     * @return
     */

    @GetMapping(value = "/sse/currentMsg/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter handleSse(@PathVariable Integer id) {
        SseEmitter emitter = new SseEmitter(60 * 1000L);
        sseEmitters.put(id, emitter);
        // 超时移除
        emitter.onTimeout(() -> {
            emitter.complete();
            sseEmitters.remove(id);
        });
        // 完成移除
        emitter.onCompletion(() -> sseEmitters.remove(id));
        // 每一秒发送一条消息
        executorService.scheduleAtFixedRate(() -> {
            ObjectMapper mapper = new ObjectMapper();
//            //if(ErrorMsgQueue.size() > 0)
//            //    collectService.sseResp.setErrorMsg(ErrorMsgQueue.pop());//6-28 演示暂时注释掉
//            //else
//            collectService.sseResp.setErrorMsg(null);

            WebResult<HardwareCurrentMessageResp> sseResp = WebResult.okResult(hardwareContactService.getCurrentMessage());
            try {
                emitter.send(SseEmitter.event().id(String.valueOf(getSseSeq())).data(mapper.writeValueAsString(sseResp), MediaType.APPLICATION_JSON));
            } catch (IOException e) {
                emitter.complete();
            }
        }, 0, 1, TimeUnit.SECONDS);

        return emitter;
    }


    /**
     * sse推送实时信息
     *
     * @param id
     * @return
     */

    @GetMapping(value = "/sse/hardwareConfig/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter configSse(@PathVariable Integer id) {
        SseEmitter emitter = new SseEmitter(60 * 1000L);
        sseEmitters.put(id, emitter);
        // 超时移除
        emitter.onTimeout(() -> {
            emitter.complete();
            sseEmitters.remove(id);
        });
        // 完成移除
        emitter.onCompletion(() -> sseEmitters.remove(id));
        // 每一秒发送一条消息
        executorService.scheduleAtFixedRate(() -> {
            ObjectMapper mapper = new ObjectMapper();
//            //if(ErrorMsgQueue.size() > 0)
//            //    collectService.sseResp.setErrorMsg(ErrorMsgQueue.pop());//6-28 演示暂时注释掉
//            //else
//            collectService.sseResp.setErrorMsg(null);

            WebResult<List<ProjectConfiguration>> sseResp = WebResult.okResult(ProjectConfigProcessService.projectConfigurations);
            try {
                emitter.send(SseEmitter.event().id(String.valueOf(getSseSeq())).data(mapper.writeValueAsString(sseResp), MediaType.APPLICATION_JSON));
            } catch (IOException e) {
                emitter.complete();
            }
        }, 0, 1, TimeUnit.SECONDS);

        return emitter;
    }
    ProcessRuntimeReq processRuntimeReq = new ProcessRuntimeReq();
    @Resource
    RunWarnService runWarnService;
    @Resource
    DGLMainProcess mainProcess;
    @Resource
    ConnectManager connectManager;
    ProcessRuntimeReq.StatusHolder statusHolder = new ProcessRuntimeReq.StatusHolder();
    @GetMapping(value = "/sse/runtimeStatus/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter runtimeSSE(@PathVariable Integer id) {
        SseEmitter emitter = new SseEmitter(60 * 1000L);
        sseEmitters.put(id, emitter);
        // 超时移除
        emitter.onTimeout(() -> {
            emitter.complete();
            sseEmitters.remove(id);
        });
        // 完成移除
        emitter.onCompletion(() -> sseEmitters.remove(id));
        // 每一秒发送一条消息
        executorService.scheduleAtFixedRate(() -> {
            ObjectMapper mapper = new ObjectMapper();
            processRuntimeReq.setWarnList(runWarnService.currentWarnList);
            BeanUtil.copyProperties(mainProcess.statusHolder,statusHolder,true);
            processRuntimeReq.setStatusHolder(statusHolder);
            processRuntimeReq.setLinkDevices(connectManager.getCurrentLink());
            if (mainProcess.childList.size()>0) {
                List<ProcessRuntimeReq.StatusHolder> statusHolders = new ArrayList<>();
                for (BaseProcess baseProcess : mainProcess.childList) {
                    ProcessRuntimeReq.StatusHolder statusHolder1 = new ProcessRuntimeReq.StatusHolder();
                    baseProcess.statusHolder.setProcessName(baseProcess.desc);
                    BeanUtil.copyProperties(baseProcess.statusHolder,statusHolder1,true);
                    statusHolders.add(statusHolder1);
                }
                processRuntimeReq.setChildStatus(statusHolders);
            }
            WebResult<ProcessRuntimeReq> sseResp = WebResult.okResult(processRuntimeReq);
            try {
                emitter.send(SseEmitter.event().id(String.valueOf(getSseSeq())).data(mapper.writeValueAsString(sseResp), MediaType.APPLICATION_JSON));
            } catch (IOException e) {
                emitter.complete();
            }
        }, 0, 1, TimeUnit.SECONDS);

        return emitter;
    }
    /**
     * 保存项目配置
     * @return /
     */
    @GetMapping("/getSSEData")
    public WebResult<HardwareCurrentMessageResp> getSSEData() {
        return WebResult.okResult(hardwareContactService.getCurrentMessage());
    }




    /**
     * 保存项目配置
     *
     * @param projectConfiguration 项目配置
     * @return /
     */
    @PostMapping("/saveProjectConfig")
    public WebResult<ProjectConfiguration> saveProjectConfig(@RequestBody ProjectConfiguration projectConfiguration) {
        ProjectConfiguration projectConfig = hardwareContactService.saveProjectConfig(projectConfiguration);
        return WebResult.okResult(projectConfig);
    }

    /**
     * 更新项目参数
     *
     * @param projectConfiguration 项目配置
     * @return /
     */
    @PostMapping("/updateProjectConfig")
    public WebResult<ProjectConfiguration> updateProjectConfig(@RequestBody ProjectConfiguration projectConfiguration) {
        log.info(projectConfiguration.toString());
        ProjectConfiguration hardwareDictionary = hardwareContactService.updateProjectConfig(projectConfiguration);
        return WebResult.okResult(hardwareDictionary);
    }

    @GetMapping("/deleteProjectConfig")
    public WebResult<String> deleteProjectConfig(Integer id) {
        hardwareContactService.deleteProjectConfig(id);
        return WebResult.okResult("执行删除操作");

    }

    @GetMapping("/getProjectConfig")
    public WebResult<List<ProjectConfiguration>> getProjectConfig() {
        return WebResult.okResult(hardwareContactService.getProjectConfig());
    }

    /**
     * 根据条件查询 项目配置
     *
     * @param queryCriteria 条件
     * @return /
     */
    @PostMapping("/getProjectConfig/condition")
    public WebResult<List<ProjectConfiguration>> getProjectConfigByProject(@RequestBody ProjectConfigQueryCriteria queryCriteria) {
        return WebResult.okResult(hardwareContactService.getProjectConfigByCondition(queryCriteria));
    }

    /*---------------------------------------- 项目参数 ----------------------------------------*/

    /**
     * 根据条件分页查询 项目配置
     *
     * @param req 条件_分页
     * @return /
     */
    @PostMapping("/getProjectConfig/condition/page")
    public WebResult<Page<ProjectConfigurationResp>> getProjectConfigPage(@RequestBody ProjectConfigReq req) {
        log.info(req.toString());
        Pageable pageable = PageRequest.of(req.getPageNumber(), req.getPageSize());
        Page<ProjectConfigurationResp> projectConfigByCondition = hardwareContactService.getProjectConfigByCondition(req.getQueryCriteria(), pageable);
        return WebResult.okResult(projectConfigByCondition);
    }

    /**
     * 保存项目参数
     *
     * @param projectParameter 项目参数
     * @return /
     */
    @PostMapping("/saveProjectParam")
    public WebResult<ProjectParameter> saveProjectParam(@RequestBody ProjectParameter projectParameter) {
        ProjectParameter projectParam = hardwareContactService.saveProjectParam(projectParameter);
        return WebResult.okResult(projectParam);
    }

    /**
     * 更新项目参数
     *
     * @param projectParameter 项目参数
     * @return /
     */
    @PostMapping("/updateProjectParam")
    public WebResult<ProjectParameter> updateProjectParam(@RequestBody ProjectParameter projectParameter) {
        ProjectParameter hardwareDictionary = hardwareContactService.updateProjectParam(projectParameter);
        return WebResult.okResult(hardwareDictionary);
    }

    @GetMapping("/deleteProjectParam")
    public WebResult<String> deleteProjectParam(Integer id) {
        hardwareContactService.deleteProjectParam(id);
        return WebResult.okResult("执行删除操作");
    }

    @GetMapping("/getProjectParam")
    public WebResult<List<ProjectParameter>> getProjectParam() {
        return WebResult.okResult(hardwareContactService.getProjectParam());
    }

    /**
     * 根据条件查询 项目参数
     *
     * @param queryCriteria 条件
     * @return /
     */
    @PostMapping("/getProjectParam/condition")
    public WebResult<List<ProjectParameter>> getProjectParamByProject(@RequestBody ProjectParamQueryCriteria queryCriteria) {
        return WebResult.okResult(hardwareContactService.getProjectParamByCondition(queryCriteria));
    }

    /*---------------------------------------- 项目硬件类型 ----------------------------------------*/

    /**
     * 根据条件分页查询 项目参数
     *
     * @param req 条件_分页
     * @return /
     */
    @PostMapping("/getProjectParam/condition/page")
    public WebResult<Page<ProjectParameter>> getProjectParamPage(@RequestBody ProjectParamReq req) {
        Pageable pageable = PageRequest.of(req.getPageNumber(), req.getPageSize());
        return WebResult.okResult(hardwareContactService.getProjectParamByCondition(req.getQueryCriteria(), pageable));
    }

    /**
     * 保存项目硬件类型
     *
     * @param hardwareTypeDict 项目硬件类型
     * @return /
     */
    @PostMapping("/saveHardwareTypeDict")
    public WebResult<HardwareTypeDict> saveHardwareTypeDict(@RequestBody HardwareTypeDict hardwareTypeDict) {
        HardwareTypeDict hardwareTypeDictResult = hardwareContactService.saveHardwareTypeDict(hardwareTypeDict);
        return WebResult.okResult(hardwareTypeDictResult);
    }

    /**
     * 更新项目硬件类型
     *
     * @param hardwareTypeDict 项目硬件类型
     * @return /
     */
    @PostMapping("/updateHardwareTypeDict")
    public WebResult<HardwareTypeDict> updateHardwareTypeDict(@RequestBody HardwareTypeDict hardwareTypeDict) {
        HardwareTypeDict hardwareTypeDictResult = hardwareContactService.saveHardwareTypeDict(hardwareTypeDict);
        return WebResult.okResult(hardwareTypeDictResult);
    }

    @GetMapping("/deleteHardwareType")
    public WebResult<String> deleteHardwareType(Integer id) {
        hardwareContactService.deleteHardwareTypeDict(id);
        return WebResult.okResult("执行删除操作");
    }

    /*---------------------------------------- 项目硬件动作 ----------------------------------------*/

    @GetMapping("/getHardwareType")
    public WebResult<List<HardwareTypeDict>> getHardwareType() {
        return WebResult.okResult(hardwareContactService.getHardwareTypeDict());
    }

    @GetMapping("/getworkplaceType")
    public WebResult<List<HardwareWorkplace>> getworkplaceType() {
        return WebResult.okResult(hardwareContactService.getworkplaceTypeDict());
    }



    /**
     * 保存项目硬件动作
     *
     * @param hardwareActionDict 项目硬件动作
     * @return /
     */
    @PostMapping("/saveHardwareAction")
    public WebResult<HardwareActionDict> saveHardwareAction(@RequestBody HardwareActionDict hardwareActionDict) {
        HardwareActionDict hardwareActionDictResult = hardwareContactService.saveHardwareActionDict(hardwareActionDict);
        return WebResult.okResult(hardwareActionDictResult);
    }

    /**
     * 更新项目硬件动作
     *
     * @param hardwareActionDict 项目硬件动作
     * @return /
     */
    @PostMapping("/updateHardwareAction")
    public WebResult<HardwareActionDict> updateHardwareAction(@RequestBody HardwareActionDict hardwareActionDict) {
        HardwareActionDict hardwareActionDictResult = hardwareContactService.updateHardwareActionDict(hardwareActionDict);
        return WebResult.okResult(hardwareActionDictResult);
    }

    @GetMapping("/getHardwareAction")
    public WebResult<List<HardwareActionDict>> getHardwareAction() {
        return WebResult.okResult(hardwareContactService.getHardwareActionDict());
    }

    /**
     * 删除硬件动作
     *
     * @param id id
     * @return /
     */
    @GetMapping("/deleteHardwareAction")
    public WebResult<String> deleteHardwareAction(Integer id) {
        hardwareContactService.deleteHardwareActionDict(id);
        return WebResult.okResult("删除执行中");
    }

    /* 硬件详情设置 */

    /**
     * 创建 硬件信息
     *
     * @param hardwareDictionary 硬件信息
     * @return /
     */
    @PostMapping("/config/saveHardwareInfo")
    public WebResult saveHardwareInfo(@RequestBody HardwareDictionary hardwareDictionary) {
        if (hardwareDictionary.getId() == 999) {
            HardwareDictionary info = hardwareContactService.saveHardwareInfo(hardwareDictionary);
            return WebResult.okResult(info);
        } else {
            return WebResult.okResult("当前id已存在");
        }
    }

    /**
     * 更新某个硬件的信息
     */
    @PostMapping("/config/updateHardwareInfo")
    public WebResult<String> updateHardwareInfo(@RequestBody HardwareInfoConfigReq hardwareInfoConfigReq) {
//        log.info("======"+hardwareInfoConfigReq.toString());
        hardwareContactService.updateHardwareInfo(hardwareInfoConfigReq);
        //更新硬件abs信息
        hardwareAbsService.updateAbsPos(hardwareInfoConfigReq.getAbsPosList(),hardwareInfoConfigReq.getId());
        //
        return WebResult.okResult("更新成功");
    }

    /**
     * 配置端-查询所有硬件的详情
     */
    @GetMapping("/config/getHardwareInfoAll")
    public WebResult<List<HardwareInfoConfigResp>> getHardwareInfoAll() {
        List<HardwareInfoConfigResp> hardwareConfigInfoAll = hardwareContactService.getHardwareConfigInfoAll();
        return WebResult.okResult(hardwareConfigInfoAll);
    }

    /**
     * 配置端-分页查询所有硬件的详情
     */
    @GetMapping("/config/getHardwareInfoAllByPage")
    public WebResult<Page<HardwareInfoConfigResp>> getHardwareInfoAllByPage(Pageable pageable) {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Pageable pageRequest = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<HardwareInfoConfigResp> hardwareConfigInfoAll = hardwareContactService.getHardwareConfigInfoAll(pageRequest);
        return WebResult.okResult(hardwareConfigInfoAll);
    }



    /**
     * 配置端-分页查询所有硬件工位的详情
     */
    @GetMapping("/getHardwareWorkplaceAllByPage")
    public WebResult<Page<HardwareWorkplace>> getHardwareWorkplaceAllByPage(Pageable pageable) {
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageRequest = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<HardwareWorkplace> hardwareWorkplacesAll = hardwareContactService.getHardwareWorkplaceAll(pageRequest);
        return WebResult.okResult(hardwareWorkplacesAll);
    }


    /**
     * 配置端-保存工位
     *
     * @param hardwareWorkplace
     * @return
     */
    @PostMapping("/saveHardwareWorkplace")
    public WebResult<HardwareWorkplace> saveHardwareWorkplace(@RequestBody HardwareWorkplace hardwareWorkplace) {
        log.info(hardwareWorkplace.toString());
        HardwareWorkplace hardwareWorkplaceResult = hardwareContactService.saveHardwareWorkplace(hardwareWorkplace);

        return WebResult.okResult(hardwareWorkplaceResult);
    }


    /**
     * 配置端-更新工位
     *
     * @param hardwareWorkplace
     * @return
     */
    @PostMapping("/updateHardwareWorkplace")
    public WebResult<HardwareWorkplace> updateHardwareWorkplace(@RequestBody HardwareWorkplace hardwareWorkplace) {
        HardwareWorkplace hardwareworkplaceResult = hardwareContactService.saveHardwareWorkplace(hardwareWorkplace);
        return WebResult.okResult(hardwareworkplaceResult);
    }



    /**
     * 配置端-删除硬件工位
     *
     * @param id id
     * @return /
     */
    @GetMapping("/deleteHardwareWorkplace")
    public WebResult<String> deleteHardwareWorkplace(Integer id) {
        hardwareContactService.deleteHardwareWorkplace(id);
        return WebResult.okResult("删除执行中");
    }




    /**
     * 配置端-查询单个硬件的详情
     */
    @GetMapping("/config/getHardwareInfoById")
    public WebResult<HardwareInfoConfigResp> getHardwareInfoById(Integer id) {
        HardwareInfoConfigResp hardwareConfigInfoById = hardwareContactService.getHardwareConfigInfoById(id);
        return WebResult.okResult(hardwareConfigInfoById);
    }

    /**
     * 删除硬件详情
     *
     * @param id id
     * @return /
     */
    @GetMapping("/config/deleteHardwareInfo")
    public WebResult<String> deleteHardwareInfo(Integer id) {
        hardwareContactService.deleteHardwareInfo(id);
        return WebResult.okResult("删除成功");
    }

    /**
     * 运行端-查询单个硬件的详情
     */
    @GetMapping("/run/getHardwareInfoById")
    public WebResult<HardwareInfoViewResp> getHardwareInfoRunById(Integer id) {
        HardwareInfoViewResp hardwareInfo = hardwareContactService.getHardwareInfo(id);
        return WebResult.okResult(hardwareInfo);
    }

    /**
     * 运行端-查询所有硬件的详情
     */
    @GetMapping("/run/getHardwareInfoAll")
    public WebResult<List<HardwareInfoViewResp>> getHardwareInfo() {
        List<HardwareInfoViewResp> hardwareInfoAll = hardwareContactService.getHardwareInfoAll();
        return WebResult.okResult(hardwareInfoAll);
    }

    /**
     * 通过工位id查询硬件信息
     * @param workplaceId
     * @return
     */

    @GetMapping("/run/getHardwareInfoByworkplaceId")
    public WebResult<List<HardwareInfoViewResp>> getHardwareInfoByworkplaceId(@RequestParam Integer workplaceId) {
        List<HardwareInfoViewResp> hardwareInfoAll = hardwareContactService.getHardwareInfoByworkplaceId(workplaceId);

        hardwareAbsService.getAbsPosValue(hardwareInfoAll);
        return WebResult.okResult(hardwareInfoAll);
    }


    /**
     * 根据工位获取IO
     *
     * @param workplaceId
     * @return
     */
    @GetMapping("/run/getConfigByworkplaceId")
    public WebResult<List<ProjectConfiguration>> getConfigByworkplaceId(@RequestParam Integer workplaceId) {
        List<ProjectConfiguration> ProjectConfigurationList = hardwareContactService.getConfigByworkplaceId(workplaceId);
        return WebResult.okResult(ProjectConfigurationList);
    }


    /**
     * 运行端-控制电机运动-参数列表
     *
     * @param req 参数列表
     * @return /
     */
    @PostMapping("/other/control/run/read")
    public WebResult<String> controlRunRead(@RequestBody ControlCmdReadReq req) {
        hardwareContactService.controlHardwareRun(req.getHardwareId(), req.getParamId());
        return WebResult.okResult("控制硬件" + req.getHardwareId() + ",参数" + req.getParamId());
    }

    /**
     * 运行端-控制电机运动-手动输入
     *
     * @param req 参数列表
     * @return /
     */
    @PostMapping("/other/control/run/set")
    public WebResult<String> controlRunSet(@RequestBody ControlCmdSetReq req) {
        hardwareContactService.controlHardwareRun(req);
        return WebResult.okResult("控制硬件" + req.getHardwareId() + ",动作" + req.getActionId());
    }

    /* 特别接口 */

    /**
     * 获取硬件协议列表
     *
     * @return /
     */
    @GetMapping("/other/getProtocolList")
    public WebResult<List<String>> getProtocolList() {
        List<String> protocolList = new ArrayList<>();
        protocolList.add(modbusTcp);
        protocolList.add(modbusRtu);
        protocolList.add(s7);
        return WebResult.okResult(protocolList);
    }

    /**
     * 获取通讯协议列表
     *
     * @return /
     */
    @GetMapping("/other/getProtocolNameList")
    public WebResult<List<String>> getProtocolNameList() {
        List<String> protocolList = new ArrayList<>();
        protocolList.add("com");
        protocolList.add("s7");
        protocolList.add("tcp_client");
        protocolList.add("tcp_server");
        return WebResult.okResult(protocolList);
    }

    /**
     * 获取通讯协议详情
     *
     * @param protocolName com/tcp
     * @return /
     */
    @GetMapping("/other/findAllProtocolList")
    public WebResult getProtocolListByName(String protocolName) {
        if (protocolName.equals("com")) {
            List<PortComm> allProtocolComm = protocolParamService.findAllProtocolComm();
            return WebResult.okResult(allProtocolComm);
        } else {
            List<PortSocket> allProtocolSocket = protocolParamService.findAllProtocolSocket();
            List<PortSocket> protocolSocket = new LinkedList<>();
            for (PortSocket portSocket : allProtocolSocket) {
                if ("s7".equals(protocolName)) {
                    log.info("暂未处理");
                } else if ("tcp_client".equals(protocolName) || "tcp_server".equals(protocolName)) {
                    String[] split = protocolName.split("_");
                    if (portSocket.getServerType().equals(split[1])) {
                        protocolSocket.add(portSocket);
                    }
                } else {
                    return WebResult.okResult(allProtocolSocket);
                }
            }
            return WebResult.okResult(protocolSocket);
        }
    }

    /**
     * 获取硬件信息 By hardwareId
     *
     * @param hardwareId
     * @return
     */
    @GetMapping("/getHardwareAbsPos")
    public WebResult getHardwareAbsPos(@RequestParam Integer hardwareId){
        return WebResult.okResult(hardwareAbsService.findHardwareAbsPosByHardwareId(hardwareId));
    }



    /**
     * 绝对位置运动
     *
     * @param req
     * @return
     */
    @PostMapping("/other/control/run/abs")
    public WebResult<String> controlRunAbs(@RequestBody ControlCmdSetReq req) {
        hardwareAbsService.controlHardwareRun(req.getAbsId());
        String s = hardwareAbsService.getAbsPosValue(req.getAbsId());
        return WebResult.okResult("控制硬件" + req.getHardwareId() + ",运动到" + s);
    }


    /**
     * 设置 plc abs位置
     *
     * @param req
     * @return
     */
    @PostMapping("/other/control/set/abs")
    public WebResult<String> controlSetAbs(@RequestBody ControlCmdSetReq req) {
        hardwareAbsService.saveAbsPos(req.getAbsId(),req.getHardwareId());
        projectConfigProcessService.readProjectConfigByAddress("DB3.0",542,0);
        ProjectConfiguration projectConfiguration = hardwareAbsService.getCurrentPosValue(req.getHardwareId());
        return WebResult.okResult("控制硬件" + req.getHardwareId() + ",设置Abs"+req.getAbsId() +"位置,为"+ projectConfiguration.getValue());
    }






    /**
     * 内存中取值
     * 根据条件分页查询 内存项目配置
     *
     * @param req 条件_分页
     * @return /
     */
    @PostMapping("/getProjectConfigRam/condition/page")
    public WebResult<Page<ProjectConfiguration>> getProjectConfigRamPage(@RequestBody ProjectConfigReq req) {
        Pageable pageable = PageRequest.of(req.getPageNumber(), req.getPageSize());
        return WebResult.okResult(hardwareContactService.getProjectConfigRamByCondition(req.getQueryCriteria(),pageable));
    }


    /**
     * 更新内存信息
     *
     * @param projectConfiguration
     * @return
     */
    @PostMapping("/update/ProjectConfigRam")
    public WebResult<String> updateProjectConfigRam(@RequestBody ProjectConfiguration projectConfiguration){
        //更新内存信息
        projectConfigProcessService.updateRamConfigurationValue(projectConfiguration.getId(),projectConfiguration.getValue());
        //更新实时推送信息
        hardwareCurrentService.updateHardwareCurrent();
        return WebResult.okResult("更新成功");
    }


    /**
     * 根据configId，修改 plc 中的值
     *
     * @param projectConfiguration
     * @return
     */
    @PostMapping("/send/ProjectConfig")
    public  WebResult<String> SendCmdPlcByConfigId(@RequestBody ProjectConfiguration projectConfiguration){
        hardwareContactService.SendCmdPlcByConfigId(projectConfiguration.getId(),projectConfiguration.getValue());
        projectConfigProcessService.readProjectConfigByAddress("DB3.0",542,0);
        return WebResult.okResult("更新成功");
    }


    /**
     * 根据address地址修改plc中的值，现临时用于 初始化、启动、停止、报警复位
     *
     * @param projectConfiguration
     * @return
     */
    @Resource
    ProcessStatusExchangeHolder processStatusExchangeHolder;
    @PostMapping("/S7Control")
    public WebResult<String> S7Control(@RequestBody ProjectConfiguration projectConfiguration){
        String address = projectConfiguration.getAddress();
        log.info("DB1."+address+"<===> 1");
        switch (address) {
            case "60" -> processStatusExchangeHolder.setAuto(false);
            case "60.1" -> processStatusExchangeHolder.setAuto(true);
            case "60.3" -> processStatusExchangeHolder.start();
            case "60.4" -> processStatusExchangeHolder.onPause();
            case "60.5" -> processStatusExchangeHolder.cancelAlarm();
            case "60.6" -> processStatusExchangeHolder.release();
        }
        return WebResult.okResult("更新成功");
    }


//    /**
//     * 修改homePos位置信息value
//     * value : currPos
//     * @param req
//     * @return
//     */
//    @PostMapping("/other/control/run/HomePos/Save")
//    public WebResult<String> saveHomePos(@RequestBody ControlCmdSetReq req) {
//
//        hardwareContactService.saveHomePos(req);
//        return WebResult.okResult("控制硬件" + req.getHardwareId() + ",动作" + req.getActionId());
//    }















}
